"""视图模块

"""

from flask import Flask, render_template, redirect, url_for, request, flash
from flask_sqlalchemy import SQLAlchemy
import click
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField
from wtforms.validators import DataRequired, Length
from .models import *
from .extensions import db, login_manager
import os
from .forms import *
from flask_login import login_user
from notes_ms import app


@app.route('/', methods=['POST', 'GET'])
def login():
    """登陆界面的视图

    """
    form = LoginForm()
    if form.validate_on_submit():
        username = form.name.data
        passwd = form.passwd.data
        admin = Admin.query.all()[0]
        if username == admin.name and passwd == admin.passwd:
            login_user(admin)
            flash('登陆成功')
            
            return redirect(url_for('index'))
        else:
            flash('用户名或者密码错误')
    else:
        print(form.errors) 
    return render_template('login.html', form=form)


@app.route('/index')
def index():
    """显示笔记的视图

    :return:
    """
    notes = Note.query.all()
    deleteSubmit = DeleteNoteForm()
    updateSubmit = UpdateNoteForm()
    return render_template('show_note.html', notes=notes, deleteSubmit=deleteSubmit, updateSubmit=updateSubmit)


@app.route('/new_note', methods=['POST', 'GET'])
def new_note():
    """添加笔记的视图函数

    :return:
    """
    form = NewNoteForm()
    if request.method == 'POST':        # TODO 验证表单
        body = form.body.data
        note = Note(body=body)
        db.session.add(note)
        db.session.commit()
        flash('保存成功')
        return redirect(url_for('index')) # 避免重复提交 重定向到显示页面
    return render_template('new_note.html', form=form)


@app.route('/delete_note/<int:note_id>', methods=['POST'])
def delete_note(note_id):
    """删除笔记的逻辑

    :param note_id: 笔记在数据库中的id
    :return:
    """
    form = DeleteNoteForm()
    if request.method == 'POST':
        note = Note.query.get(note_id)
        db.session.delete(note)
        db.session.commit()
        flash('删除笔记成功')
    return redirect(url_for('index'))


@app.route('/update_note/<int:note_id>', methods=['POST', 'GET'])
def update_note(note_id):
    """修改笔记内容的逻辑

    :param note_id:
    :return:
    """

    note = Note.query.get(note_id)
    form = UpdateNoteForm()

    if request.method == 'POST':  # TODO 验证表单
        note.body = form.body.data
        print(form.body.data)
        db.session.commit()
        flash('修改成功')
        return redirect(url_for('index'))  # 避免重复提交 重定向到显示页面
    if request.method == 'GET':
        """如果是GET请求仅仅渲染表单，同时带上数据库中笔记内容"""
        form.body.data = note.body
        return render_template('update_note.html', form=form)